package com.cloudeoffice.server.service.impl;

import com.cloudeoffice.server.pojo.Admin;
import com.cloudeoffice.server.pojo.Menu;
import com.cloudeoffice.server.mapper.MenuMapper;
import com.cloudeoffice.server.pojo.Role;
import com.cloudeoffice.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudeoffice.server.util.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liujingnu
 * @since 2022-03-15
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    //根据用户id查询菜单列表
    @Override
    public List<Menu> getMenusByAdmin() {
        //因为使用了 spring security ，而用户登录后直接从全局中取出对象
        Integer adminId= AdminUtils.getCurrentAdmin().getId();
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        //查询缓冲中是否有数据
        List<Menu> menus =(List<Menu>) valueOperations.get("menu_" + adminId);
        if (CollectionUtils.isEmpty(menus)){
            //如果没有数据，则数据库中查询，并放入缓存里
           menus= menuMapper.getMenusByAdmin(adminId);
           valueOperations.set("menu_" + adminId,menus);

        }
        return menus;
    }
    //根据角色获取菜单列表
    @Override
    public List<Menu> getAllMenusWithRole() {
        return menuMapper.getAllMenusWithRole();
    }
    //获取所有菜单
    public List<Menu> getAllMenus(){
        return menuMapper.getAllMenus();
    }
}
